package selef.xiafan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import selef.xiafan.entity.system.SysPermission;
import selef.xiafan.query.SysPermissionQ;
import selef.xiafan.service.ISysPermissionService;
import selef.xiafan.util.result.PageResult;
import selef.xiafan.util.result.Result;
import selef.xiafan.util.result.ResultFactory;

import java.util.List;

/**
 * @author xiafan
 * @version 1.0
 * @date 2021/7/1 23:22
 */
@RestController
@CrossOrigin
@RequestMapping("/api")
public class SysPermissionC {
    @Autowired
    private ISysPermissionService iSysPermissionService;

    @GetMapping("/system/user")
    public List<SysPermission> listUser() throws Exception {
        return iSysPermissionService.list();
    }

    @GetMapping("/permission/listPermission")
    public Result listPermissiion() {
        return ResultFactory.buildSuccessResult(iSysPermissionService.getAll());
    }

    @GetMapping("/permission/menu")
    public Result menuList() {
        List<SysPermission> menus = iSysPermissionService.getMenusByCurrentUser();
        return ResultFactory.buildSuccessResult(menus);
    }

    @PostMapping("/permission/listPermission")
    public PageResult<SysPermission> listPermission(@RequestBody SysPermissionQ sysPermissionQ) {
        return iSysPermissionService.listPermission(sysPermissionQ);
    }

    @GetMapping("/permission/menu/menuParents")
    public Result parentMenu() {
        return new ResultFactory().buildSuccessResult(iSysPermissionService.getAllByParentId(0));
    }

    @GetMapping("/permission/menu/listMenus")
    public Result listMenus() {
        return new ResultFactory().buildSuccessResult(iSysPermissionService.getMenuList(1));
    }

    @PostMapping("/permission/menu/addPermission")
    public Result addPermissionMenus(@RequestBody SysPermission sysPermission){
        int result = iSysPermissionService.addOrUpdate(sysPermission);
        if(result==1){
            return ResultFactory.buildSuccessResult("权限添加成功");
        }
        if(result==2){
            return ResultFactory.buildSuccessResult("权限修改成功");
        }
        if(result==3){
            return ResultFactory.buildFailResult("此权限为父节点，不能作为子节点");
        }
        return ResultFactory.buildFailResult("程序异常");

    }

    @PostMapping("/permission/delete")
    public Result delte(@RequestBody SysPermission sysPermission){
        int delete = iSysPermissionService.delete(sysPermission);
        if(delete==0){
            return ResultFactory.buildSuccessResult("删除成功");
        }
        if(delete==1){
            return ResultFactory.buildFailResult("该父节点下存在子节点，不能删除");
        }
        return ResultFactory.buildFailResult("删除失败");
    }
}
